// src/hooks/useTokenContract.ts
import { useState, useEffect, useCallback } from 'react';
import { ethers } from 'ethers';
import VSampleToken from '../abis/VSampleToken.json';

const contractAddress = import.meta.env.VITE_CONTRACT_ADDRESS;


type ClaimStatus = {
  canClaim: boolean;
  availableToday: number;
  remainingTotal: number;
};

export function useTokenContract() {
  const [provider, setProvider] = useState<ethers.BrowserProvider | null>(null);
  const [signer, setSigner] = useState<ethers.JsonRpcSigner | null>(null);
  const [contract, setContract] = useState<ethers.Contract | null>(null);
  const [account, setAccount] = useState<string | null>(null);
  const [isOwner, setIsOwner] = useState(false);
  const [claimStatus, setClaimStatus] = useState<ClaimStatus | null>(null);
  const [contractBalance, setContractBalance] = useState<string>("0");
  const [userBalance, setUserBalance] = useState<string>("0");
  const [initialized, setInitialized] = useState(false);


  const resetState = () => {
    setAccount(null);
    setContract(null);
    setSigner(null);
    setProvider(null);
    setIsOwner(false);
    setClaimStatus(null);
    setContractBalance("0");
    setUserBalance("0");
    setInitialized(false);
  };


  // 初始化以太坊提供者和合约
  useEffect(() => {
    if (window.ethereum) {
      const init = async () => {
        const provider = new ethers.BrowserProvider(window.ethereum);
        setProvider(provider);

        const signer = await provider.getSigner();
        setSigner(signer);

        const contract = new ethers.Contract(
          contractAddress,
          VSampleToken.abi,
          signer
        );
        setContract(contract);


        const accounts = await provider.listAccounts();
        if (accounts.length > 0) {
          const address = accounts[0].address;
          setAccount(address);

        
        // 检查是否是owner
        const owner = await contract.owner();
        setIsOwner(address.toLowerCase() === owner.toLowerCase());

        // 初始化数据
        await updateBalances(contract, address);
        await updateClaimStatus(contract, address);
        }
        setInitialized(true);
      };

      init();
      console.log("claimStatus updated:", claimStatus); // 每次更新时触发

      const handleAccountsChanged = (accounts: string[]) => {
        console.log("accounts changed:", accounts);
        if (accounts.length === 0) {
          // 用户断开了授权，清空状态
          resetState();
        } else {
          console.log("new accounts:", accounts);
          setAccount(accounts[0]);
          if (contract && accounts[0]) {
            updateBalances(contract, accounts[0]);
            updateClaimStatus(contract, accounts[0]);
            contract.owner().then((owner: string) => {
              setIsOwner(accounts[0].toLowerCase() === owner.toLowerCase());
            });
          }
        }
      };

      window.ethereum.on('accountsChanged', handleAccountsChanged);

    }
  }, []);

  const updateBalances = async (contract: ethers.Contract, account: string) => {
    const contractBal = await contract.balanceOf(contractAddress);
    const userBal = await contract.balanceOf(account);
    setContractBalance(ethers.formatEther(contractBal));
    setUserBalance(ethers.formatEther(userBal));
  };


  const updateClaimStatus = async (contract: ethers.Contract, account: string) => {
    const status = await contract.getClaimStatus(account);

    const newStatus = {
      canClaim: status[0],
      availableToday: Number(status[1]),
      remainingTotal: Number(ethers.formatEther(status[2]))
    };
    if (
      claimStatus?.canClaim === newStatus.canClaim &&
      claimStatus?.availableToday === newStatus.availableToday &&
      claimStatus?.remainingTotal === newStatus.remainingTotal
    ) {
      return; // 数据无变化，不触发更新
    }
    console.log("Raw status:", status);
    // console.log('status', status);
    // console.log('status[0]', status[0]);
    // console.log('status[1]', status[1]);
    setClaimStatus({
      canClaim: status[0],
      availableToday: Number(status[1]),
      remainingTotal: Number(ethers.formatEther(status[2]))
    });

  };

  const claimTokens = async () => {
    if (!contract) return;
    try {
      const tx = await contract.claim();
      await tx.wait();
      if (account) {
        updateBalances(contract, account);
        updateClaimStatus(contract, account);
      }
      return true;
    } catch (error) {
      console.error("Claim error:", error);
      return false;
    }
  };

  const withdrawTokens = async (amount: string, to: string) => {
    if (!contract || !isOwner) return false;
    try {
      const tx = await contract.withdrawRemaining(
        to,
        ethers.parseEther(amount)
      );
      await tx.wait();
      if (account) {
        updateBalances(contract, account);
      }
      return true;
    } catch (error) {
      console.error("Withdraw error:", error);
      return false;
    }
  };
  // 用户点击连接时调用
  const connectWallet = async () => {
    if (!window.ethereum) {
      alert("请安装MetaMask!");
      return;
    }

    try {
      const provider = new ethers.BrowserProvider(window.ethereum);
      const accounts = await provider.send("eth_requestAccounts", []);

      const signer = await provider.getSigner();
      const contract = new ethers.Contract(contractAddress, VSampleToken.abi, signer);

      setProvider(provider);
      setSigner(signer);
      setContract(contract);
      setAccount(accounts[0]);

      // 初始化数据
      console.log("连接成功:", accounts[0]);
      await updateBalances(contract, accounts[0]);

      await updateClaimStatus(contract, accounts[0]);
      setInitialized(true);
    } catch (error) {
      console.error("连接失败:", error);
    }
  };
  return {
    provider,
    signer,
    contract,
    account,
    isOwner,
    claimStatus,
    contractBalance,
    userBalance,
    claimTokens,
    withdrawTokens,
    updateClaimStatus: () => account && contract && updateClaimStatus(contract, account),
    updateBalances: () => account && contract && updateBalances(contract, account),
    connectWallet,
    initialized
  };
}